package org.akomantoso.core.io.util;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.akomantoso.core.data.PreambleoptElement;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;
import org.akomantoso.core.io.util.group.BlockElementsGroup;
import org.akomantoso.core.io.util.group.PreambleContainersGroup;
import org.akomantoso.core.util.MapUtil;

/**
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 */
public final class PreambleoptElementUtil {

	private PreambleoptElementUtil() {
	}

	public static final Map<String, Instantiator<PreambleoptElement>> MAP;

	public static PreambleoptElement instantiate(String elementName) {

		final Instantiator<PreambleoptElement> instatiator = MAP.get(elementName);
		if (instatiator == null) {
			throw new RuntimeException("Tag [" + elementName + "] not supported ?!?");
		}
		return instatiator.instantiate();

	}
	
	public static void read(Input in,List<PreambleoptElement> elements, final String localName) throws IOException {

		PreambleoptElement element = null;
		
		while(true) {
			
			switch (in.getEventType()) {
			case InputConstants.START_ELEMENT:
				elements.add(element = instantiate(in.getLocalName()));
				element.readExternal(in);
				break;			
			case InputConstants.END_ELEMENT:
				if (localName.equals( in.getLocalName())) {
					return;
				} 
			}
			
			in.readNext();
		}
	}

	static {
		Map<String, Instantiator<PreambleoptElement>> temp = new HashMap<String, Instantiator<PreambleoptElement>>();
		MapUtil.copy(BlockElementsGroup.MAP, temp);
		MapUtil.copy(PreambleContainersGroup.MAP, temp);
		MAP = Collections.unmodifiableMap(temp);
	}
}
